package leetcode.weekly.week293;

import leetcode.templates.trees.segment.StNode;

public class CountIntervals {

	Node root;

	public CountIntervals() {
		root = new Node(1, (int) 1e9);
	}

	public void add(int left, int right) {
		root.add(left, right);
	}

	public int count() {
		return root.count;
	}

	class Node {

		private int LeftRange, Mid, RightRange;
		private Node leftChild, rightChild;
		private Integer value;

		private int count;

		public Node(int left, int right) {
			this.LeftRange = left;
			this.RightRange = right;
			this.Mid = ((this.RightRange - this.LeftRange) >> 1) + this.LeftRange;
			this.value = 0;
			this.count = 0;
		}

		public int size() {
			return this.RightRange - this.LeftRange + 1;
		}

		private Node leftNode() {
			if (this.leftChild == null) {
				this.leftChild = new Node(this.LeftRange, this.Mid);
			}
			return this.leftChild;
		}

		private Node rightNode() {
			if (this.rightChild == null) {
				this.rightChild = new Node(this.Mid + 1, this.RightRange);
			}
			return this.rightChild;
		}

		private void addValue(int value) {
			this.value = this.value == null ? value : this.value + value;
		}

		public void add(int left, int right) {
			if (left > right || this.count == this.RightRange - this.LeftRange + 1) {
				return;
			}
			if (left == this.LeftRange && right == this.RightRange) {
				this.count = right - left + 1;
//				this.addValue(add);
				return;
			} else {
//				pushdown();
				this.leftNode().add(left, Math.min(this.Mid, right));
				this.rightNode().add(Math.max(this.Mid + 1, left), right);
				this.count = this.leftNode().count + this.rightNode().count;
			}
		}

		public int query(int index) {
			if (this.LeftRange == index && index == this.RightRange) {
				return value;
			}
//			pushdown();
			if (index <= this.Mid) {
				return this.leftNode().query(index);
			}
			return this.rightNode().query(index);
		}

//
//		private void pushdown() {
//			if (this.count != 0) {
//				this.leftNode().count = this.leftNode().size();
//				this.rightNode().count = this.rightNode().size();
//				this.count = 0;
//			}
//		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
